package udf.matching;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Hashtable;
import java.util.Iterator;

import org.apache.pig.EvalFunc;
import org.apache.pig.data.DataBag;
import org.apache.pig.data.Tuple;
import org.apache.pig.data.TupleFactory;

public class EncodeAgeType extends EvalFunc<Tuple> {

	
	
	/**
	 * Codes
	 * 
	 * 0   nothing
	 * 1 kids 
	 * 2 teens
	 * 3 mteens
	 * 4 adults
	 * 5 kids, teens mteens
	 * 6 kids, teens
	 * 7 teen , mteens
	 * 8  kids, adults
	 * 9  other
	 * 
	 * 
	 */
	public Tuple exec(Tuple input) throws IOException {

		int k = 0;
		int t = 0;
		int m = 0;
		int a = 0;
		int ktm = 0;
		int kt = 0;
		int tm = 0;
		int ka = 0;

		if (input != null && input.size() > 0) {

			DataBag bag = (DataBag) input.get(0);

			if (bag != null) {

				Iterator<Tuple> iterator = bag.iterator();

				while (iterator.hasNext()) {

					Tuple tup = iterator.next();
					if (tup != null && tup.size() > 0) {
						String type = (String) tup.get(0);
						if (type != null) {

							type = type.trim();

							if (type.equals("kids")) {
								k = 1;

							} else if (type.equals("teens")) {

								t = 1;
							} else if (type.equals("mteens")) {
								m = 1;
							} else if (type.equals("adults")) {
								a = 1;
							} else if (type.equals("kids-teens")) {
								kt = 1;
							} else if (type.equals("kids-teens-mteens")) {
								ktm = 1;
							} else if (type.equals("teens-mteens")) {
								tm = 1;
							}

						}

					}
				}
			}
		}
			int code=0;
		
		if(k ==1 && checkActive(t,m, a,kt,ktm,tm)){			
			code=1;			
		}else if(t ==1 && checkActive(k,a,m ,kt,ktm,tm)){
			code=2;
		}else if(m ==1 && checkActive(k,t,a,kt,ktm,tm)){
			code=3;
		}else if(a==1 && checkActive(k,t, m,kt,ktm,tm)){
			code=4;
		}else if(ktm ==1 && checkActive(k,t,m,a,kt,tm)){
			code=5;
		}else if(kt ==1 && checkActive(k,t,m,a,ktm,tm)){
			code=6;
		}else if(tm ==1 && checkActive(k,t,m,a,ktm,tm)){
			code=7;
		}else if(k ==1 && a ==1){
			code=8;
		}else{
			code=-1;
		}
		
		
		
		
		
		
		Tuple output = TupleFactory.getInstance().newTuple();
		output.append(code);		
	
		return output;

	}

	private boolean checkActive(int t, int m, int a, int kt, int ktm, int tm) {
		// TODO Auto-generated method stub
		
		int sum = t+a + kt+ktm + tm+ m ;
		
		if(sum==0) return true;
		
		return false;
	}
	
	
	
}
